package com.msb.mall.producet.service.impl;

import com.msb.common.constant.ProductConstant;
import com.msb.mall.producet.dao.AttrAttrgroupRelationDao;
import com.msb.mall.producet.dao.AttrGroupDao;
import com.msb.mall.producet.entity.*;
import com.msb.mall.producet.service.AttrAttrgroupRelationService;
import com.msb.mall.producet.service.AttrGroupService;
import com.msb.mall.producet.service.CategoryService;
import com.msb.mall.producet.vo.AttrGroupRelationVO;
import com.msb.mall.producet.vo.AttrResponseVO;
import com.msb.mall.producet.vo.AttrVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.producet.dao.AttrDao;
import com.msb.mall.producet.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrGroupDao attrGroupDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVO vo) {
        //保存规格参数的正常信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(vo, attrEntity);
        this.save(attrEntity);

        //保存规格参数和属性组的对应信息
        if (vo.getAttrGroupId() != null && attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity en = new AttrAttrgroupRelationEntity();
            en.setAttrId(attrEntity.getAttrId());
            en.setAttrGroupId(vo.getAttrGroupId());
            attrAttrgroupRelationService.save(en);
        }
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", attrType.equalsIgnoreCase("base") ? 1 : 0);
        //1.根据类别编号查询
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        //2.根据key 模糊查询
        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        //3.分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        //4.查询出类别名称和属性组名称
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVO> datas = records.stream().map(attrEntity -> {
            AttrResponseVO attrResponseVO = new AttrResponseVO();
            BeanUtils.copyProperties(attrEntity, attrResponseVO);
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVO.setCatelogName(categoryEntity.getName());
            }
            if ("base".equalsIgnoreCase(attrType)) {
                Optional.ofNullable(attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())))
                        .ifPresent(obj -> {
                            if (obj.getAttrGroupId() != null) {
                                Optional.ofNullable(attrGroupService.getById(obj.getAttrGroupId())).ifPresent(obj1 -> {
                                    attrResponseVO.setGroupName(obj1.getAttrGroupName());
                                });
                            }

                        });
            }
            return attrResponseVO;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(datas);

        return pageUtils;
    }

    /**
     * 根据规格参数Id查询对应的详细信息
     * 1. 规格参数的具体信息
     * 2. 关联的属性组信息
     * 3. 关联的类别信息
     * @param attrId
     * @return
     */
    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {
        AttrResponseVO responseVO = new AttrResponseVO();
        //查询基本信息
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, responseVO);

        //查询关联的属性组信息  --中间表
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                responseVO.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    responseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //查询关联的类别信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        responseVO.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if (categoryEntity != null) {
            responseVO.setCatelogName(categoryEntity.getName());
        }

        return responseVO;
    }

    @Override
    public void updateBaseAttr(AttrVO attr) {
        //更新基础数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //修改分组关联的关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            //判断是否存在对应的数据
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                //有记录  更新
                attrAttrgroupRelationService.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                //没有记录  新增
                attrAttrgroupRelationDao.insert(relationEntity);

            }
        }
    }

    @Transactional
    @Override
    public void removeByIdsDeatils(Long[] attrIds) {

        for (Long attrId : attrIds) {
            AttrEntity attrEntity = getById(attrId);
            if (attrEntity != null && attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
                //还需要删除关联的属性组的中间表信息
                attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            }
        }

        //1.删除基本属性表中的数据
        this.removeByIds(Arrays.asList(attrIds));
    }

    /**
     * 根据属性组编号查询对应属性信息
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //1.根据属性组编号从 属性组和基本信息的关联表中查询出对应的属性信息
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        //2.根据属性编号查询出对应的属性信息
        List<AttrEntity> attrEntities = list.stream().map(e -> this.getById(e.getAttrId()))
                .filter(e -> e != null)
                .collect(Collectors.toList());


        return attrEntities;
    }

    /**
     * 解除属性组和基本属性的关联关系
     *    --也就是删除关联表的记录
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        List<AttrAttrgroupRelationEntity> list = Arrays.asList(vos).stream().map(vo -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.removeBatchRelation(list);
    }

    /**
     * 根据属性组的id 查询没有关联的属性信息
     * 1.查询出所有的属性信息
     *          我们找到的属性信息必须是和属性组的类别相同的属性
     * 2.查询出当前属性组关联的信息
     * 3.  从1中排除掉2中的属性信息
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        //1.查询出当前属性组所在的类别编号
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        //获取对应的分类id
        Long catelogId = attrGroupEntity.getCatelogId();

        //2.当前分组只能关联自己所属的类别下 其他分组没有关联的属性信息
        //2.1先找到这个类别下所有的分组信息
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 获取属性组的编号集合
        List<Long> groupIds = group.stream().map(e -> e.getAttrGroupId()).collect(Collectors.toList());

        //然后查询出属性组类别信息下所有的属性组已经分配的属性信息
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = relationEntities.stream().map(e -> e.getAttrId()).collect(Collectors.toList());

        //根据类别编号查询所有的属性信息并排除掉上面的属性信息即可
        //这其实就是需要查询出最终返回给调用着的信息    分页   带条件查询
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id", catelogId)
                //排除掉销售信息
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds!= null && attrIds.size() > 0) {
            //排除掉已经关联的属性信息
            wrapper.notIn("attr_id", attrIds);
        }

        //根据key模糊查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<AttrEntity> list = this.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds).eq("search_type", 1));
        if (list != null && list.size() > 0) {
            return list.stream().map(e -> e.getAttrId()).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }


}